package com.yy.glide;

import com.yy.glide.recycle.BitmapPool;
import com.yy.glide.recycle.LruBitmapPool;
import com.yy.glide.recycle.Resource;

public class CacheTest implements LruMemoryCache.ResourceRemoveListener, Resource.ResourceListener {
    private LruMemoryCache mLruMemoryCache;
    private ActiveResource mActiveResource;
    private BitmapPool mBitmapPool;

    public Resource test(Key key) {
        mBitmapPool = new LruBitmapPool(10);
        mLruMemoryCache = new LruMemoryCache(10);
        mLruMemoryCache.setResourceRemoveListener(this);
        mActiveResource = new ActiveResource(this);

        Resource resource = mActiveResource.get(key);
        if (resource != null) {
            resource.acquire();
            return resource;
        }

        resource = mLruMemoryCache.get(key);
        if (resource != null) {
            resource.acquire();
            mActiveResource.active(key, resource);
            mLruMemoryCache.removeResource(key);
            return resource;
        }
        return null;
    }

    /**
     * 内存缓存被动移除 ,放入复用池
     *
     * @param resource
     */
    @Override
    public void onResourceRemove(Resource resource) {
        mBitmapPool.put(resource.getBitmap());
    }

    /**
     * 从活动缓存加入到内存缓存
     *
     * @param key
     * @param resource
     */
    @Override
    public void onResourceReleased(Key key, Resource resource) {
        mActiveResource.removeActive(key);
        mLruMemoryCache.put(key, resource);
    }
}
